﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Krile.Kernel;
using Krile.Kernel.Plugin;
using System.Runtime.InteropServices;

namespace Yukkrile
{
    public class YOperation : Krile.Kernel.Plugin.Operation
    {
        Plugin parent;
        public YOperation(Plugin parent)
        {
            this.parent = parent;
            Bridge.KeyAssign.AddAssignCandidateMethod(new Krile.Kernel.Data.Common.KeyAssignCallback(TalkThis), "選択中のステータスを読み上げます。");
        }

        public void TalkThis(Krile.Kernel.Bridges.IForm form, Krile.Kernel.Data.Status s, System.Windows.Forms.Keys k)
        {
            var a = new Action<string>(Core.SendMessage);
            a.BeginInvoke(s.User.Name + "の発言、" + s.Text.Original + "、" + s.ParentService.Name + "から。",
                (iar) => ((Action<string>)iar.AsyncState).EndInvoke(iar), a);
        }

        public override string ParentPluginId
        {
            get { return Define.PluginId; }
        }

        public override Operation.OperationTypes OperationType
        {
            get { return OperationTypes.Other; }
        }

        public override void Begin()
        {
            Core.Init(parent);
            Bridge.StatusManager.OnStatusRegistered += new Krile.Kernel.Data.Common.StatusRegistedCallback(StatusManager_OnStatusRegistered);
        }

        void StatusManager_OnStatusRegistered(IEnumerable<Krile.Kernel.Data.Status> statuses)
        {
            if (Core.Config.AutoRead)
            {
                var ss = from s in statuses
                         orderby s.CreatedAt descending
                         select s;
                int ctor = 3;
                foreach (var s in ss)
                {
                    ctor--;
                    if (ctor < 0)
                        break;
                    TalkThis(null, s, System.Windows.Forms.Keys.None);
                }
            }
        }

        public override void Exit()
        {
            Core.Exit();
        }

        public override Dictionary<string, Krile.Kernel.Control.ConfigPage> GetConfigPages()
        {
            var d = new Dictionary<string, Krile.Kernel.Control.ConfigPage>();
            d.Add("置き換えテーブル", new ConfigPage());
            return d;
        }
    }
}
